<template>
    <el-main class="container-box">
        <div class="container-content">
            <h4> <b>学生界面控制</b></h4>
            <el-form v-loading="loading" label-position="top" label-width="210px" class="permission-form">
                <!-- 权限控制部分 -->
                <el-form-item v-for="section in permissionSections" :key="section.title" class="permission-section">
                    <template #label>
                        <b class="section-header">{{ section.title }}</b>
                    </template>
                    <div v-for="item in section.items" :key="item.routerName" class="permission-item">
                        <div class="permission-name">{{ item.label }}</div>
                        <el-radio-group v-model="permissionMap[item.routerName]" class="permission-options">
                            <el-radio v-for="(option, k) in item.options" :key="`k-${option.label}`"
                                :value="option.value">
                                {{ option.label }}
                            </el-radio>
                        </el-radio-group>
                    </div>
                </el-form-item>
                <!-- AI功能开关部分 -->
                <el-form-item v-if="false" class="permission-section">
                    <template #label>
                        <b class="section-header">AI功能控制</b>
                    </template>
                    <el-form-item v-for="(item, idx) in aiSwitches" :key="item.prop" class="AI-item" :label="item.label"
                        :prop="item.prop">
                        <el-switch v-model="aiSettings[item.prop]" inline-prompt active-text="显示" inactive-text="隐藏"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                    </el-form-item>
                </el-form-item>

                <div class="form-actions margin-top20">
                    <el-button size="default" type="primary" @click="start">刷新</el-button>
                    <el-button size="default" type="primary" @click="submitupdate">保存</el-button>
                </div>
            </el-form>
        </div>
    </el-main>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { computed, onMounted, ref } from 'vue';
import { useStore } from 'vuex';
import { asynccreateteamrole, asyncgetteam, asyncteamchangeteam, selectteamrole } from '../../../api';
import { Storekey } from '../../../interface';
import Studycodemodel from '../../../mysql_interface/studycodemodel';

const store = useStore(Storekey);
const user = computed(() => store.state.user);
const teamId = computed(() => user.value?.teamid);
const loading = ref(false)

const permissionSections = [
    {
        title: '导航栏',
        items: [
            { label: '评测列表', routerName: '评测', options: [{ value: true, label: '全员（含学生）可见' }, { value: false, label: '仅老师管理员可见' }] }
        ]
    },
    {
        title: '比赛',
        items: [
            { label: '比赛总结', routerName: '比赛总结', options: [{ value: true, label: '学生可查看其他学生总结' }, { value: false, label: '学生仅可查看自己的比赛总结' }] }
        ]
    },
    {
        title: '题目练习',
        items: [
            // { label: '我的提交', routerName: '我的提交', options: [{ value: true, label: '全员（含学生）可见' }, { value: false, label: '仅老师、管理员可见' }] },
            { label: '题目题解', routerName: '题目题解', options: [{ value: true, label: '全员（含学生）可见' }, { value: false, label: '仅老师、管理员可见' }] },
            // { label: '题目讨论', routerName: '题目讨论', options: [{ value: true, label: '全员（含学生）可见' }, { value: false, label: '仅老师、管理员可见' }] },
            // { label: '思路提示', routerName: '思路提示', options: [{ value: true, label: '全员（含学生）可见' }, { value: false, label: '仅老师、管理员可见' }] }
        ]
    },
];
// 权限映射表
const permissionMap = ref<Record<string, boolean | string>>({});
const currentRole = ref<any>(null);

const aiSwitches: { label: string, prop: keyof typeof aiSettings.value }[] = [
    { label: 'AI思路提示', prop: 'ideaTips' },
    { label: 'AI代码协助', prop: 'codeHelp' },
    // { label: 'AI分析比赛', prop: 'activitySummarize' },
    // { label: 'AI分析比赛成员', prop: 'activityUserSummarize' }
];
// AI功能设置
const aiSettings = ref({ ideaTips: false, codeHelp: false, activitySummarize: false, activityUserSummarize: false });
// 团队原始配置
const originalTeamData = ref<any>(null);

// 从接口数据初始化权限
function initPermissions(teamData: { role: Studycodemodel.Iteamrole | null, other: any }) {
    // 初始化权限设置
    if (teamData.role) {
        currentRole.value = teamData.role;
        permissionSections.forEach(section => {
            section.items.forEach(item => {
                permissionMap.value[item.routerName] = teamData.role?.routername?.includes(item.routerName) || false;
            });
        });
    } else {
        permissionSections.forEach(section => {
            section.items.forEach(item => {
                permissionMap.value[item.routerName] = false;
            });
        });
    }
    // 初始化AI设置
    if (teamData.other) {
        aiSettings.value = {
            ideaTips: teamData.other?.ideaTips,
            codeHelp: teamData.other?.codeHelp,
            activitySummarize: teamData.other?.activitySummarize,
            activityUserSummarize: teamData.other?.activityUserSummarize
        };
    }
}
// 获取权限数据
async function start() {
    loading.value = true
    try {
        const { rows } = await selectteamrole({ teamid: teamId.value, name: '学生' });
        // 获取团队配置数据
        const teamData = await asyncgetteam({ ID: teamId.value });
        originalTeamData.value = teamData;
        // 初始化数据
        initPermissions({
            role: rows.length > 0 ? rows[0] : null,
            other: teamData.other || {}
        });
    } catch (error) {
        ElMessage.error('获取权限失败');
    }
    loading.value = false
}
async function submitupdate() {
    try {
        const enabledPermissions = Object.entries(permissionMap.value).filter(([_, value]) => value === true).map(([key]) => key);
        console.log(enabledPermissions, aiSettings.value)
        await asynccreateteamrole({
            ID: currentRole.value?.ID,
            teamid: teamId.value,
            name: '学生',
            routername: enabledPermissions
        });
        // 保存AI设置 - 保留原始other中的其他字段
        await asyncteamchangeteam({
            ID: teamId.value,
            teamid: teamId.value,
            other: {
                ...originalTeamData.value?.other,  // 保留原始other中的所有字段
                ...aiSettings.value               // 只覆盖AI相关字段
            }
        });
        ElMessage.success('保存成功');
        start();
    } catch (error) {
        ElMessage.error('保存失败');
        console.error('保存失败:', error);
    }
}
onMounted(() => {
    start();
});
</script>

<style scoped>
.container-box {
    padding: 0;

    --margin-bottom: 10px;
}

.permission-form {
    padding: 0 20px;
}

.permission-section {
    padding-top: var(--margin-bottom);
    margin-bottom: calc(var(--margin-bottom) * 2);
    border-bottom: 1px solid #eee;
}

.section-header {
    font-size: 18px;
}

.permission-item {
    display: flex;
    align-items: center;
    width: 100%;
    margin: var(--margin-bottom) 0;
}

.permissionAI-item {
    display: flex;
}

.permission-name {
    width: 120px;
    font-size: 14px;
    color: #666;
}

.permission-options {
    flex: 1;

    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.AI-item {
    min-width: 180px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: var(--margin-bottom) 0;
}

.form-actions {
    text-align: center;
}

.el-radio {
    margin-right: 24px;
}
</style>
<style>
.AI-item .el-form-item__label {
    margin: 0;
}
</style>